﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Device.Location;
using System.Windows.Media;
using Microsoft.Phone.Controls.Maps;
using Microsoft.Phone.Controls;
using System.Collections.ObjectModel;
using System.Net.NetworkInformation;
using GlobalRadar.Language;

namespace GlobalRadar
{
    class MapDraw
    {
        Map myMap;

        public MapDraw(Map map)
        {
            this.myMap = map;
        }

        Dictionary<string, MapPolygon> Polygons { get; set; }
        Dictionary<string, MapPolyline> Polylines{ get; set; }
        Dictionary<string, Pushpin> Pushpins { get;set; }
        List<Pushpin> Trackers { get; set; }
        Dictionary<string, MapLayer> Maplayers { get; set; }
        MapPolygon Circle = new MapPolygon();
        Pushpin myPushpin = new Pushpin();
        Pushpin selected = new Pushpin();

        public void CreateDataRadar()
        {
            MapPolyline line = new MapPolyline();
            
            line.Locations = new LocationCollection();
            line.Stroke = new SolidColorBrush(Colors.Green);
            line.Opacity = 0.7;
            line.StrokeThickness = 5;

            Circle.Stroke = new SolidColorBrush(Color.FromArgb(100, 255, 0, 0));
            Circle.Fill = new SolidColorBrush(Color.FromArgb(100, 42, 180, 58));
            Circle.StrokeThickness = 10;
            Circle.Opacity = 0.8;
            Circle.BorderBrush = new SolidColorBrush(Colors.Green);

            myPushpin.Content = App.LangVN == true ? ResourceVN.MeHere : ResourceEn.MeHere;

            Pushpin FindPushpin = new Pushpin();
            FindPushpin.Content = App.LangVN == true ? ResourceVN.DrawFind : ResourceEn.DrawFind;
            FindPushpin.Tap += PushpinTap;
            
            MapLayer mapRoute = new MapLayer(); 

            Add("myLocation", myPushpin, true);
            Add("mapRoute", mapRoute, true);
            Add("FindLocation", FindPushpin, true);
            Add("finger", line, true);
            Add("circle", Circle, true);

        }
        protected void PushpinTap(object sender,System.Windows.Input.GestureEventArgs e)
        {
            var _ppmodel = sender as Pushpin;
            
            if (_ppmodel == null) return;

            selected = _ppmodel;

            ContextMenu contextMenu = new ContextMenu();

            MenuItem Route = new MenuItem() { Header = (App.LangVN == true ? ResourceVN.DrawMenuRoute : ResourceEn.DrawMenuRoute) };

            Route.Click += MenuClickItem_Click;
            
            contextMenu.Items.Add(Route);

            ContextMenuService.SetContextMenu(_ppmodel, contextMenu);
            
            contextMenu.IsOpen = true;
        }
        void MenuClickItem_Click(object sender, EventArgs e)
        {
            var menu = sender as MenuItem;

            if (menu != null && selected!=null)
            {
                string text = menu.Header.ToString().ToLower();

                if (text == (App.LangVN == true ? ResourceVN.DrawMenuRoute.ToLower() : ResourceEn.DrawMenuRoute.ToLower()))
                {
                    List<GeoCoordinate> locations = new List<GeoCoordinate>();
                    locations.Add(myPushpin.Location);
                    locations.Add(selected.Location);

                    GetRouteLine(locations);

                    //ShowItem("FindLocation");
                    //mapdraw.PushpinUpdateLocation("FindLocation", e.Result.Results[0].Locations[0]);
                    //MapControl.Center = e.Result.Results[0].Locations[0];
                }
            }
            
        }
        private void GetRouteLine(List<GeoCoordinate> locations)
        {
            if (NetworkInterface.GetIsNetworkAvailable() != true) return;

            MapLayer RouteLayer = new MapLayer();

            BingMapRoute.RouteServiceClient routeService = new BingMapRoute.RouteServiceClient("BasicHttpBinding_IRouteService");

            routeService.CalculateRouteCompleted += (sender, e) =>
            {
                var points = e.Result.Result.RoutePath.Points;

                var coordinates = points.Select(x => new GeoCoordinate(x.Latitude, x.Longitude));

                var routeColor = Colors.Blue;

                var routeBrush = new SolidColorBrush(routeColor);

                var routeLine = new MapPolyline()
                {
                    Locations = new LocationCollection(),
                    Stroke = routeBrush,
                    Opacity = 0.65,
                    StrokeThickness = 5.0,
                };

                foreach (var location in points)
                {
                    routeLine.Locations.Add(new GeoCoordinate(location.Latitude, location.Longitude));
                }
                //RouteLayer.Children.Add(routeLine);
                UpdateMaplayer("mapRoute", routeLine);
                ShowItem("mapRoute");
            };

            routeService.CalculateRouteAsync(new BingMapRoute.RouteRequest()
            {
                Credentials = new Credentials()
                {
                    ApplicationId = "Ah04k4eCmb7IC1gG50_ToWNRSBrBcx2CBCumfzID0bI1bRvUKEDt2y6r1Htpo6kG"
                },
                Options = new BingMapRoute.RouteOptions()
                {
                    RoutePathType = BingMapRoute.RoutePathType.Points
                },
                Waypoints = new ObservableCollection<BingMapRoute.Waypoint>(
                    locations.Select(x => new BingMapRoute.Waypoint()
                    {
                        Location = x
                    }))
            });
        }
        public void Add(string Text,MapPolygon polygon, bool isEnabled)
        {
            if (Polygons == null)
            {
                Polygons = new Dictionary<string, MapPolygon>();
            }

            if (Polygons.ContainsKey(Text)) { return; }

            polygon.IsEnabled=isEnabled;

            Polygons.Add(Text, polygon);
        }
        public void Add(string Text, MapPolyline polyline, bool isEnabled)
        {
            if (Polylines == null)
            {
                Polylines = new Dictionary<string, MapPolyline>();
            }

            if (Polylines.ContainsKey(Text)) { return; }

            polyline.IsEnabled = isEnabled;

            Polylines.Add(Text, polyline);
        }
        public void Add(string Text, Pushpin pushpin, bool isEnabled)
        {
            if (Pushpins == null)
            {
                Pushpins = new Dictionary<string, Pushpin>();
            }

            if (Pushpins.ContainsKey(Text)) { return; }

            pushpin.IsEnabled = isEnabled;

            pushpin.Tap += PushpinTap;

            Pushpins.Add(Text, pushpin);
        }
        public void Add(string Text, MapLayer mapLayer, bool isEnabled)
        {
            if (Maplayers == null)
            {
                Maplayers = new Dictionary<string, MapLayer>();
            }

            if (Maplayers.ContainsKey(Text)) { return; }

            Maplayers.Add(Text, mapLayer);
        }
        public void AddTrack(Pushpin pushpin)
        {
            if (Trackers == null)
            {
                Trackers = new List<Pushpin>();
            }

            if (Trackers.Contains(pushpin)) { return; }

            pushpin.Tap += PushpinTap;

            Trackers.Add(pushpin);
        }
        public void ShowItem(params string[] Texts)
        {
            foreach (string text in Texts)
            {
                if (Polygons != null && Polygons.ContainsKey(text))

                    if(!myMap.Children.Contains(Polygons[text]))
                    {
                        myMap.Children.Add(Polygons[text]);
                    }
                if (Polylines != null && Polylines.ContainsKey(text))

                    if (!myMap.Children.Contains(Polylines[text]))
                    {
                        myMap.Children.Add(Polylines[text]);
                    }
                if (Pushpins !=null && Pushpins.ContainsKey(text))

                    if (!myMap.Children.Contains(Pushpins[text]))
                    {
                        myMap.Children.Add(Pushpins[text]);
                    }
                if (Maplayers != null && Maplayers.ContainsKey(text))

                    if (!myMap.Children.Contains(Maplayers[text]))
                    {
                        myMap.Children.Add(Maplayers[text]);
                    }
            }
        }
        public void ShowAllTrack()
        {
            if (Trackers == null) return;

            foreach (Pushpin item in Trackers)
            {
                if(Circle.Contains(item.Location))
                {
                    if (!myMap.Children.Contains(item))
                    {
                        myMap.Children.Add(item);
                    }
                }
            }
        }
        public void RemoveItem(params string[] Texts)
        {
            foreach (string text in Texts)
            {
                if(Polygons.ContainsKey(text))

                    if (myMap.Children.Contains(Polygons[text]))
                    {
                        myMap.Children.Remove(Polygons[text]);
                    }
                if (Polylines.ContainsKey(text))

                    if (myMap.Children.Contains(Polylines[text]))
                    {
                        myMap.Children.Remove(Polylines[text]);
                    }
                if (Pushpins.ContainsKey(text))

                    if (myMap.Children.Contains(Pushpins[text]))
                    {
                        myMap.Children.Remove(Pushpins[text]);
                    }
                if (Maplayers.ContainsKey(text))

                    if (myMap.Children.Contains(Maplayers[text]))
                    {
                        myMap.Children.Remove(Maplayers[text]);
                    }
            }
        }
        public void RemoveAllTrack()
        {
            if (Trackers == null) return;

            foreach (Pushpin item in Trackers)
            {
                if (myMap.Children.Contains(item))
                {
                    myMap.Children.Remove(item);
                }
            }
        }
        public void PolygonDraw(string Text,GeoCoordinate Location,double Zoom)
        {
            if (Polygons.ContainsKey(Text))
            {
                Polygons[Text].DrawCircler(Location, Zoom);
            }
        }
        public void PolyLineDraw(string Text, GeoCoordinate BeginLocation, GeoCoordinate EndLocation)
        {
            if (Polylines.ContainsKey(Text))
            {
                Polylines[Text].DrawLine(BeginLocation,EndLocation);
            }
        }
        public void Clear()
        {
            myMap.Children.Clear();
        }
        public void ClearTrackTemp()
        {
            if (Trackers == null) return;
            RemoveAllTrack();
            Trackers.Clear();
        }
        public void ClearPushpin()
        {
            foreach (System.Windows.UIElement chil in myMap.Children)
            {
                if (chil is Pushpin)
                {
                    myMap.Children.Remove(chil);
                }
            }
            Pushpins.Clear();
        }
        public void PushpinUpdateLocation(string Text, GeoCoordinate Location)
        {
            if (Pushpins.ContainsKey(Text))
            {
                Pushpins[Text].Location=Location;
            }
        }
        public GeoCoordinate GetPushpinLocation(string Text)
        {
            if (Pushpins.ContainsKey(Text))
            {
                return Pushpins[Text].Location;
            }
            return null;
        }
        public void UpdateMaplayer(string Text, MapPolyline routeline)
        {
            if (Maplayers.ContainsKey(Text))
            {
                Maplayers[Text].Children.Clear();
                Maplayers[Text].Children.Add(routeline);
            }
        }
    }
}
